<?php
class Mailbox_model extends BZ_Model
{
    protected $table = 'mailbox';

    function findById($id)
    {
        $this->db->select('id, fid, sid, ftime, attribute, type, title, content, fname, sname');
        $this->db->from($this->table);
        $this->db->where('id', $id);
        $this->db->limit(1);
        return $this->db->get();
    }
    
    public function findByParam($params=array())
    {
        if (!empty($params['type'])) {
            $this->db->where('type', $params['type']);
        }
        if (!empty($params['user_type'])) {
            $this->db->where(('sid & '.$params['user_type']));
        }
        $this->db->order_by('id', 'DESC');
        $this->db->limit($params['limit']);
        return $this->db->get($this->table);
    }
    
    public function total($params=array())
    {
        if (!empty($params['type'])) {
            $this->db->where('type', $params['type']);
        }
        if (!empty($params['user_type'])) { //用户类型
            $this->db->where(('sid & '.$params['user_type']));
        }
        if (!empty($params['sid'])) { //收件人
            $this->db->where('sid', $params['sid']);
        }
        if (!empty($params['fid'])) { //发件
            $this->db->where('fid', $params['fid']);
        }
        return $this->db->count_all_results($this->table);
    }
    
    public function page_list($page_num, $num, $params=array())
    {
        if (!empty($params['type'])) {
            $this->db->where('type', $params['type']);
        }
        if (!empty($params['user_type'])) { //用户类型
            $this->db->where(('sid & '.$params['user_type']));
        }
        if (!empty($params['sid'])) { //收件人
            $this->db->where('sid', $params['sid']);
        }
        if (!empty($params['fid'])) { //发件
            $this->db->where('fid', $params['fid']);
        }
        $this->db->order_by('id','DESC');
        $this->db->limit($page_num, $num);
        return $this->db->get($this->table);
    }

    public function insertMailbox($postData)
    {
        $data = array(
            'fid'       => $this->uid,
            'sid'       => $postData['sid'],
            'ftime'     => date('Y-m-d H:i:s'),
            'attribute' => 0,
            'type'      => $postData['type'],
            'title'     => $postData['title'],
            'content'   => $postData['content'],
            'fname'     => $this->userName,
            'sname'     => $postData['sname']
        );

        return $this->db->insert($this->table, $data);
    }
    /**
     * 标记为已读
     * @param $id
     * @return mixed
     */
    public function updateRead($id)
    {
        $this->db->set('attribute', 1);
        $this->db->where('id', $id);
        return $this->db->update($this->table);
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     */
    function delete($id)
    {
        $this->db->where('id', $id);
        return $this->db->delete($this->table);
    }

}